const app = getApp();

Page({
  data: {
    book: {
      title: '',
      author: '',
      publisher: '',
      publicationYear: '',
      isbn: '',
      bookCondition: '',
      price: '',
      description: '',
      imageUrl: '',
      category: '',
      sellerId: '',
    },
    url: ''
  },

  onLoad() {
    this.setData({
      url: app.imgUrl
  })
  wx.stopPullDownRefresh()
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    console.log(e)
    this.setData({
      [`book.${field}`]: e.detail
    });
    console.log(this.data.book)
  },
  onPullDownRefresh(){
    this.onLoad()
},
  publishBook() {
    const token = wx.getStorageSync('token');
    if(!token){
      wx.showToast({
        title: '你还没有登录',
        icon:'error'
      })
      return
    }
    console.log(this.data.book)
    const book = this.data.book
    wx.request({
      url: `${app.apiUrl}/books/publish`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        token: token
      },
     
      data: book,
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({ title: '发布成功', icon: 'success' });
          wx.navigateBack();
        } else {
          wx.showToast({ title: '发布失败', icon: 'error' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'error' });
      }
    });
  },

  uploadImage() {
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: res => {
        const imageUrl = res.tempFilePaths[0];
        
        // 上传到服务器
        wx.uploadFile({
          url: `${app.apiUrl}/common/upload`, // 替换为你的上传接口地址
          filePath: imageUrl,
          name: 'file', // 这里的 name 要与后端 MultipartFile 参数名一致
          success: uploadRes => {
              console.log(uploadRes)
              const data = JSON.parse(uploadRes.data);
              console.log(data)
              this.setData({
                'book.imageUrl': data // 假设后端返回的图片地址在 fileName 字段
              });
              wx.showToast({ title: '上传成功', icon: 'success' });
              console.log(this.data.book.imageUrl)
          },
          fail: () => {
            wx.showToast({ title: '上传失败', icon: 'error' });
          }
        });
      }
    });
  }
  
});
